<?php
/**
 * 心愿单管理控制器
 * User: zero
 * Date: 2015/9/20
 * Time: 21:51
 */
namespace Addons\UserCenter\Controller;
use Home\Controller\AddonsController;

class WishController extends AddonsController
{
    function _initialize()
    {
        //粉丝登录
        if (session('is_follow_login') == 1) {
            if (empty(session('user_auth')) && empty(session('oauth2'))) {
                if (isset($_GET['code'])) {
                    getUserInfo();
                } else {
                    wx_login(GetCurUrl());
                }
            }
            C('EDITOR_UPLOAD.rootPath', './Uploads/Editor/' . get_token() . '/');
        }

    }

    public function add(){
        $openid = $map ['openid'] = session('oauth2.openid');
        $token = $map ['token'] = get_token();
        if($openid == -1 || $token == -1){
            $this->error('非法访问');
        }
        $html = 'moblieForm';
        $model = $this->getModel ( 'wish' );
        $fields = get_model_attribute ( $model ['id'] );
        $fieldArr = array('content'); //headimgurl
        foreach($fields[1] as $k=>$vo){
            if(!in_array($vo['name'], $fieldArr))
                unset($fields[1][$k]);
        }
        $config = getAddonConfig ( 'UserCenter' );
        $this->assign('backbround', $config['wishBackbround']);
        $this->assign('map', $map);
        $this->assign ( 'fields', $fields );
        $this->meta_title = $this->title = '填写心愿单';

        $this->assign('post_url', U('update'));

        $this->display($html);
    }

    /**
     * 处理添加wish操作
     */
    public function update(){
        $model = $this->getModel( 'wish' );
        $Model = D( parse_name( get_table_name( $model ['id'] ), 1 ) );
        $map = [
            'openid' => session('oauth2.openid'),
            'token' => get_token(),
        ];
        if($map['openid'] == -1 || $map['token'] == -1){
            $this->error('非法访问');
        }
        $_POST = array_merge($_POST, $map);
        // 获取模型的字段信息
        $Model = $this->checkAttr( $Model, $model ['id'] );
        if ($data = $Model->create()) {
            if($data['id']){
                $where['id'] = $data['id'];
                $res = $Model->where ( $where )->save ();
            }else{
                $res = $Model->add();
            }
            if($res !== false){
                $this->success('我们已收到您的愿望！', addons_url('UserCenter://UserCenter/userCenter'), $map, 3);
            }else{
                $this->error($Model->getError());
            }
        }else{
            $this->error($Model->getError());
        }
    }
}